import hmac
import hashlib
import time
from urllib.parse import urlencode

def generate_signature(params, app_secret):
    filtered_params = {k: v for k, v in params.items() if k != "sign"}
    sorted_params = sorted(filtered_params.items())
    str_to_sign = '&'.join([f"{k}={v}" for k, v in sorted_params])
    signature = hmac.new(app_secret.encode(), str_to_sign.encode(), hashlib.sha256).hexdigest()
    return signature

def extract_params(method, query_params, body_params):
    params = {k: v for k, v in query_params.items() if v and str(v).strip()}
    if method in ["POST", "PUT", "PATCH", "DELETE"]:
        if isinstance(body_params, dict):
            for key, value in body_params.items():
                if isinstance(value, list):
                    params[key] = ','.join(map(str, value))
                else:
                    params[key] = str(value)
        else:
            raise ValueError("Unsupported request body format")
    return params


class BuildClient:
    def build_get_param(self, params):
        timestamp = str(int(time.time()))
        params['app_id'] = self.app_id
        params['timestamp'] = timestamp
        params['sign'] = generate_signature(extract_params("GET", params, params), self.app_secret)
        return params

    def build_post_param(self, params):
        timestamp = str(int(time.time()))
        params['app_id'] = self.app_id
        params['timestamp'] = timestamp
        params['sign'] = generate_signature(extract_params("POST", {}, params), self.app_secret)
        return params
